﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
using System.Data;
using System.Data.SqlClient;
using Dos.ORM;
using System.IO;

namespace TimerTool
{
    class fsl
    {
        public DateTime dts { get; set; }
        public void dojob()
        {
            string url_app = System.Configuration.ConfigurationManager.AppSettings["url"].ToString();
            DateTime dtnow = DateTime.Now;
            if (dts != null && dts > DateTime.MinValue)
            {
                dtnow = dts;
            }

            try
            {
                string baseurl = url_app + "?uid={0}&tid={1}&type={2}&pm={3}";
                int lxsj = 5;
                string sql = "";

                //每次都要判断是否有要到期的竞赛团需要发送消息


                try
                {
                    if (dtnow.Hour == 3 && dtnow.Minute < lxsj)
                    {
                        sql = string.Format(@"
                            SELECT SUM(1) as su, fxuid  from yd_user where fxuid > 0 and fxdate = '{0}'
                                GROUP BY fxuid
                        ", DateTime.Now.ToString("yyyy-MM-dd"));
                    }


                    var tm = Db.GetDb().From<yd_team>().Where(d => d.type == 1 && d.edate <= dtnow && d.edate > dtnow.AddMinutes(-5)).ToList();
                    if (tm != null && tm.Count > 0)
                    {
                        foreach (var t in tm)
                        {
                            //循环每一个team
                            //循环team里面的每一个人
                            var ydj = Db.GetDb().From<yd_data_js>().Where(d => d.tid == t.id).ToList();

                            //获取全部的排名数据的dt
                            sql = @"SELECT A.*,@rank:=@rank+1 AS pm  
                             FROM     
                             (    
                              SELECT  uid ,id FROM yd_data_js where tid = " + t.id.ToString() + @"   ORDER BY isend DESC , enddate asc ,speed DESC ,isstart DESC ,startdate asc  
                             ) A ,(SELECT @rank:=0) B ";
                            DataTable dt = MysqlHelper.ExecuteDataTable(sql, null);
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                foreach (var yd in ydj)
                                {
                                    int id = yd.uid;
                                    //调用url发送
                                    DataRow[] drr = dt.Select("uid=" + id.ToString());
                                    if (drr != null && drr.Count() > 0)
                                    {
                                        DataRow dr = drr[0];
                                        string pm = dr["pm"].ToString();
                                        string url = string.Format(baseurl, id, yd.tid, "timer_bsjs_js", pm);
                                        string re = GetUrlData(url);
                                        Dos.Common.LogHelper.Error("myjob_timer_bsjs_js_" + id + "_" + re);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Dos.Common.LogHelper.Error("timer_bsjs_js_Exception" + ex.Message.ToString());
                }

                //7点钟的 10000 步团;
                if (dtnow.Hour == 19 && dtnow.Minute < lxsj)
                {
                    Dos.Common.LogHelper.Error("myjob_19");

                    string jstype = "10000";
                    //查询所有参加了 10000步团的人.
                    sql = string.Format(@"
                            select DISTINCT c.id as uid,a.id as tid from yd_team a 
                            inner join yd_data b on a.id = b.tid and a.jstype='{1}' and a.edate >='{0}'
                            INNER JOIN yd_user c on b.uid = c.id
                        ", DateTime.Now.ToString("yyyy-MM-dd"), jstype);

                    try
                    {
                        DataTable dt = Db.GetDb().FromSql(sql).ToDataTable();
                        foreach (DataRow dr in dt.Rows)
                        {
                            int  uid = Convert.ToInt32(dr["uid"].ToString());
                            int tid = Convert.ToInt32(dr["tid"].ToString());

                            //调用url发送 g给用户送kb 也在这个接口里面实现
                            string url = string.Format(baseurl, uid, tid, jstype, 0);
                            string re = GetUrlData(url);
                        }
                    }
                    catch (Exception ex)
                    {
                        Dos.Common.LogHelper.Error("myjob_10000_Exception" + ex.Message.ToString());
                    }
                }


                if (dtnow.Hour == 22 && dtnow.Minute < lxsj)
                {
                    try
                    {
                        Dos.Common.LogHelper.Error("myjob_10");

                        sql = string.Format(@"
                            SELECT SUM(1) as su, fxuid  from yd_user where fxuid > 0 and fxdate = '{0}'
                                GROUP BY fxuid
                        ", DateTime.Now.ToString("yyyy-MM-dd"));

                        try
                        {
                            DataTable dt = Db.GetDb().FromSql(sql).ToDataTable();
                            string name = "fxjl";
                            var item = Db.GetDb().From<yd_admin_config>().Where(d => d.group == "xcx" && d.name == name).ToFirst();
                            int jl = Convert.ToInt32(item.value);

                            foreach (DataRow dr in dt.Rows)
                            {
                                int fxuid = Convert.ToInt32(dr["fxuid"].ToString());
                                int su = Convert.ToInt32(dr["su"].ToString());
                                su = jl * su;

                                //调用url发送 g给用户送kb 也在这个接口里面实现
                                string url = string.Format(baseurl, fxuid, su, name, 0);
                                string re = GetUrlData(url);
                            }
                        }
                        catch (Exception ex)
                        {
                            Dos.Common.LogHelper.Error("myjob_10_Exception" + ex.Message.ToString());
                        }

                    }
                    catch (Exception ex)
                    {
                        Dos.Common.LogHelper.Error("myjob_10_error_" + ex.Message.ToString());
                    }
                }

                if (dtnow.Hour == 0 && dtnow.Minute < lxsj)
                {
                    try
                    {
                        Dos.Common.LogHelper.Error("myjob_1");
                        //清空 stepday 的数据
                        sql = " update yd_data set stepday=0 where stepday != 0 ";
                        Db.GetDb().FromSql(sql).ExecuteNonQuery();

                        sql = " update yd_team set isjs=1 where  edate='" + dtnow.AddDays(-1).ToString("yyyy-MM-dd") + " 23:59:59' ";
                        Db.GetDb().FromSql(sql).ExecuteNonQuery();

                        sql = "delete from yd_data_day_gc where udate <'" + DateTime.Now.AddDays(-10).ToString("yyyy-MM-dd") + "'";
                        Db.GetDb().FromSql(sql).ExecuteNonQuery();

                        sql = "delete from yd_jk_log where credate <'" + DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd") + "'";
                        Db.GetDb().FromSql(sql).ExecuteNonQuery();

                        //得到F:/Temp文件夹下所有.jpg图片文件E:\backup
                        DirectoryInfo di = new DirectoryInfo(@"E:/backup");
                        FileInfo[] fi = di.GetFiles();

                        DateTime dtNow = DateTime.Now;
                        foreach (FileInfo tmpfi in fi)
                        {
                            if (tmpfi.Name.Substring(0,2) == "bk")
                            {
                                //tmpfi.CreationTime;//创建时间
                                TimeSpan ts = dtNow.Subtract(tmpfi.CreationTime);
                                if (ts.TotalDays > 15)//距现在15天以上
                                {
                                    tmpfi.Delete();//删除文件
                                }
                            }
                        }
                        
                    }
                    catch (Exception ex)
                    {
                        Dos.Common.LogHelper.Error("myjob_1_error_" + ex.Message.ToString());
                    }
                }

                yd_admin_config item_1 = null, item_2 = null, item_3 = null, item_4 = null;
                if (dtnow.Hour > 6)
                {
                    Dos.Common.LogHelper.Error("myjob_3");
                    try
                    {
                        //先处理 4. 如果有一天步数空缺，第二天（晚上8点，时间可配置）向参与者推送消息。
                        string name = "timer_nodk_time";
                        item_1 = Db.GetDb().From<yd_admin_config>().Where(d => d.group == "xcx" && d.name == name).ToFirst();

                        name = "timer_bsjs_time";
                        item_2 = Db.GetDb().From<yd_admin_config>().Where(d => d.group == "xcx" && d.name == name).ToFirst();

                        name = "timer_bsjsq_time";
                        item_3 = Db.GetDb().From<yd_admin_config>().Where(d => d.group == "xcx" && d.name == name).ToFirst();

                        name = "timer_2day_time";
                        item_4 = Db.GetDb().From<yd_admin_config>().Where(d => d.group == "xcx" && d.name == name).ToFirst();

                    }
                    catch (Exception ex)
                    {
                        Dos.Common.LogHelper.Error(ex.Message.ToString());
                    }

                    if (item_1 != null)
                    {

                        double ts = Convert.ToDouble(item_1.value);
                        DateTime dtdk1 = dtnow.Date.AddHours(ts);//20:00
                        DateTime dtdk = dtnow.Date.AddHours(ts).AddMinutes(lxsj);//20:10

                        //Dos.Common.LogHelper.Error("myjob_4_" + dtnow.ToString("yyyy-MM-dd HH:mm:ss"));
                        //Dos.Common.LogHelper.Error("myjob_4_" + dtdk1.ToString("yyyy-MM-dd HH:mm:ss"));
                        //Dos.Common.LogHelper.Error("myjob_4_" + dtdk.ToString("yyyy-MM-dd HH:mm:ss"));
                        if (dtdk1 <= dtnow && dtnow < dtdk)
                        {
                            Dos.Common.LogHelper.Error("myjob_timer_ts_nodk_1");
                            //查询出需要发送提醒的用户
                            //判断昨天的步数为空缺

                            string d1 = dtnow.AddDays(-1).ToString("yyyy-MM-dd");
                            string d2 = dtnow.ToString("yyyy-MM-dd");
                            string d3 = dtnow.AddDays(-6).ToString("yyyy-MM-dd");

                            sql = string.Format(@"
                            SELECT * from (
                                SELECT id from yd_user where id not in (
                                    SELECT  a.uid as uid from (
									    SELECT uid from yd_data_day where udate  = '{0}' 
									    union 
									    SELECT uid from yd_data_day where udate = '{1}' 
	                                ) a 
                                ) 
                            ) a 
                            INNER JOIN (
	                            SELECT DISTINCT uid as uid from yd_user_tm 
	                            where stime >='{2} 00:00:00'
                            ) b on a.id = b.uid
                        ", d1, d2, d3);
                            try
                            {
                                DataTable dt = Db.GetDb().FromSql(sql).ToDataTable();

                                foreach (DataRow dr in dt.Rows)
                                {
                                    int id = Convert.ToInt32(dr["id"].ToString());
                                    //调用url发送
                                    string url = string.Format(baseurl, id, 0, "timer_nodk_time", 0);

                                    string re = GetUrlData(url);
                                    Dos.Common.LogHelper.Error("myjob_timer_ts_nodk_" + id + "_" + re);
                                }
                            }
                            catch (Exception ex)
                            {
                                Dos.Common.LogHelper.Error("myjob_timer_ts_nodk_Exception" + ex.Message.ToString());
                            }

                        }
                    }

                    //开始匹配 发送结束的团

                    if (item_2 != null)
                    {
                        double ts = Convert.ToDouble(item_2.value);
                        DateTime dtdk1 = dtnow.Date.AddHours(ts);//22:00
                        DateTime dtdk = dtnow.Date.AddHours(ts).AddMinutes(lxsj);//22:10
                        if (dtdk1 <= dtnow && dtnow < dtdk)
                        {
                            Dos.Common.LogHelper.Error("myjob_timer_ts_bsjs_1");

                            //获取今天到期的团
                            DateTime de = Convert.ToDateTime(dtnow.ToString("yyyy-MM-dd") + " 23:59:59");
                            var list = Db.GetDb().From<yd_team>().Where(a => a.edate == de && a.jstype == "").ToList();
                            foreach (yd_team team in list)
                            {
                                string d1 = dtnow.AddDays(-1).ToString("yyyy-MM-dd");
                                string d2 = dtnow.ToString("yyyy-MM-dd");
                                string d3 = dtnow.AddDays(-6).ToString("yyyy-MM-dd");

                                sql = string.Format(@"
                            SELECT a.uid,a.rownum, ifnull(b.uid,0) as bb from (
                            SELECT *,  (@rownum:=@rownum+1) AS rownum from yd_data ,(SELECT @rownum:= 0 ) r  
		                            where tid = {0}  ORDER BY step desc 
                             ) a left  JOIN (
		                            SELECT DISTINCT uid as uid from yd_user_tm 
		                            where stime >='{1} 00:00:00'
                            ) b on a.uid = b.uid
                            WHERE  b.uid is not null ORDER BY a.rownum asc
                        ", team.id.ToString(), d3);

                                try
                                {
                                    DataTable dt = Db.GetDb().FromSql(sql).ToDataTable();
                                    foreach (DataRow dr in dt.Rows)
                                    {
                                        int id = Convert.ToInt32(dr["uid"]);
                                        int rownum = Convert.ToInt32(dr["rownum"]);
                                        //调用url发送 
                                        string url = string.Format(baseurl, id, team.id, "timer_bsjs_time", rownum.ToString());
                                        string re = GetUrlData(url);
                                        Dos.Common.LogHelper.Error("myjob_timer_ts_bsjs_" + id + "_" + re);
                                    }

                                }
                                catch (Exception ex)
                                {
                                    Dos.Common.LogHelper.Error("myjob_timer_ts_bsjs_Exception" + ex.Message.ToString());
                                }
                            }

                        }
                    }

                    if (item_3 != null)
                    {
                        double ts = Convert.ToDouble(item_3.value);
                        DateTime dtdk1 = dtnow.Date.AddHours(ts);//22:00
                        DateTime dtdk = dtnow.Date.AddHours(ts).AddMinutes(lxsj);//22:10
                        if (dtdk1 <= dtnow && dtnow < dtdk)
                        {
                            Dos.Common.LogHelper.Error("myjob_timer_ts_bsjsq_1");

                            //获取今天到期的团 的前一天 所以这里加一天就可以了
                            DateTime de = Convert.ToDateTime(dtnow.AddDays(1).ToString("yyyy-MM-dd") + " 23:59:59");
                            var list = Db.GetDb().From<yd_team>().Where(a => a.edate == de && a.jstype == "").ToList();
                            foreach (yd_team team in list)
                            {
                                string d1 = dtnow.AddDays(-1).ToString("yyyy-MM-dd");
                                string d2 = dtnow.ToString("yyyy-MM-dd");
                                string d3 = dtnow.AddDays(-6).ToString("yyyy-MM-dd");

                                sql = string.Format(@"
                            SELECT a.uid,a.rownum, ifnull(b.uid,0) as bb from (
                            SELECT *,  (@rownum:=@rownum+1) AS rownum from yd_data ,(SELECT @rownum:= 0 ) r  
		                            where tid = {0}  ORDER BY step desc 
                             ) a left  JOIN (
		                            SELECT DISTINCT uid as uid from yd_user_tm 
		                            where stime >='{1} 00:00:00'
                            ) b on a.uid = b.uid
                            WHERE  b.uid is not null ORDER BY a.rownum asc
                        ", team.id.ToString(), d3);

                                try
                                {
                                    DataTable dt = Db.GetDb().FromSql(sql).ToDataTable();

                                    foreach (DataRow dr in dt.Rows)
                                    {
                                        int id = Convert.ToInt32(dr["uid"]);
                                        int rownum = Convert.ToInt32(dr["rownum"]);
                                        //调用url发送 
                                        string url = string.Format(baseurl, id, team.id, "timer_bsjsq_time", rownum.ToString());
                                        string re = GetUrlData(url);
                                        Dos.Common.LogHelper.Error("myjob_timer_ts_bsjsq_" + id + "_" + re);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Dos.Common.LogHelper.Error("myjob_timer_ts_bsjsq_Exception" + ex.Message.ToString());
                                }
                            }

                        }
                    }


                    if (item_4 != null)
                    {
                        double ts = Convert.ToDouble(item_4.value);
                        DateTime dtdk1 = dtnow.Date.AddHours(ts);//22:00
                        DateTime dtdk = dtnow.Date.AddHours(ts).AddMinutes(lxsj);//22:05
                        if (dtdk1 <= dtnow && dtnow < dtdk)
                        {
                            Dos.Common.LogHelper.Error("myjob_tm_team_user2day_1");

                            //获取昨天开的团
                            DateTime de = dtnow.AddDays(-1).Date;
                            DateTime de2 = Convert.ToDateTime(dtnow.ToString("yyyy-MM-dd") + " 23:59:59");
                            var list = Db.GetDb().From<yd_team>().Where(a => a.bdate == de && a.edate != de2 && a.jstype == "").ToList();
                            foreach (yd_team team in list)
                            {

                                try
                                {
                                    int id = team.cuid;
                                    int rownum = team.usernum;
                                    //调用url发送 
                                    string url = string.Format(baseurl, id, team.id, "timer_2day_time", rownum.ToString());
                                    string re = GetUrlData(url);
                                    Dos.Common.LogHelper.Error("myjob_tm_team_user2day_" + id + "_" + re);
                                }
                                catch (Exception ex)
                                {
                                    Dos.Common.LogHelper.Error("myjob_tm_team_user2day_Exception" + ex.Message.ToString());
                                }
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {

            }
        }

        public string GetUrlData(string Url)
        {
            System.Net.WebRequest hr = System.Net.HttpWebRequest.Create(Url);
            hr.Method = "GET";
            System.Net.WebResponse response = hr.GetResponse();
            System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
            string ReturnVal = reader.ReadToEnd();
            reader.Close();
            response.Close();
            return ReturnVal;
            //return "xxxx";
        }

        private void AddLog(string title, string message)
        {

        }
    }
}